package com.dora.basic.juc;

/**
 * 线程本地示例
 *
 * @author hanchen
 * @date 2024/02/20
 */
public class ThreadLocalExample {

    /**
     * 创建一个 ThreadLocal 对象，用于存储线程局部变量
     */
    private static final ThreadLocal<Integer> THREAD_LOCAL_VALUE = new ThreadLocal<>();

    // 线程执行的任务
    static class Task implements Runnable {
        private final int value;

        Task(int value) {
            this.value = value;
        }

        @Override
        public void run() {
            // 将当前线程的局部变量设置为指定值
            THREAD_LOCAL_VALUE.set(value);
            System.out.println(Thread.currentThread().getName() + ": ThreadLocal value set to " + value);

            // 模拟其他操作
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 获取当前线程的局部变量值
            int retrievedValue = THREAD_LOCAL_VALUE.get();
            System.out.println(Thread.currentThread().getName() + ": Retrieved ThreadLocal value: " + retrievedValue);
        }
    }

    public static void main(String[] args) {
        // 创建两个线程执行任务,互相的数据不会影响
        Thread t1 = new Thread(new Task(10));
        Thread t2 = new Thread(new Task(20));

        t1.start();
        t2.start();
    }
}
